<template>
  <div class="media-carousel-wrap" style="width: 100%;height: 100%">
    <template v-for="(item,index) in list" :key="index">
      <video
          @ended="changeMedia"
          :src="item.finallyUrl"
          v-if="item.type==='mp4'"
          :ref="'media'+index"
          v-show="indexPlay === index"
      />
      <img
          :src="item.finallyUrl"
          alt=""
          v-else
          :ref="'media'+index"
          v-show="indexPlay === index"
      />
    </template>
  </div>
</template>

<script>
/*
*图片媒体播放器，兼容Vue2和Vue3，数据需要按格式提前组装好
*
* interface ListItemProps{
  finallyUrl:string;
  id:number;
  type:"mp4"|"image"
}
* const list:ListItemProps[]=[ {finallyUrl:"http://10.10.239.182:8000/api/upPath/PRODUCT/video/319a85fc08ff41198d7847685d49067f.mp4",id:3,type:"mp4"}]
*
* */

export default {

  props: {
    delay: {
      type: Number,
      required: true
    },
    list: {
      type: Array,
      required: true,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      loopTimer: null,
      indexPlay: 0,
    }
  },
  watch: {
    list() {
      this.initMedia()
    }
  },
  beforeUnmount() {
    clearTimeout(this.loopTimer)
  },
  methods: {
    initMedia() {
      this.$nextTick(() => {
        let isVideo = this.list[0].type === 'mp4';
        if (isVideo) {
          this.$refs['media' + this.indexPlay][0].play()
        } else {
          this.changeMedia();
        }
        console.log(this.$refs['media' + this.indexPlay][0])
      })
    },
    changeMedia() {
      clearTimeout(this.loopTimer)
      this.loopTimer = setTimeout(() => {
        this.indexPlay++;
        if (this.indexPlay === this.list.length) {
          this.indexPlay = 0;
        }
        let isVideo = this.list[this.indexPlay].type === 'mp4'
        if (isVideo) {
          this.$refs['media' + this.indexPlay][0].play()
        } else {
          this.changeMedia()
        }
      }, this.delay);
    },
  }
}
</script>
<style lang="scss" scoped>
.media-carousel-wrap {
  text-align: center;
  img {
    max-width: 100%;
    height: 100%;
  }

  video {
    max-width: 100%;
    height: 100%;
    object-fit: fill;

    &:focus {
      outline: none;
    }
  }
}
</style>
